import { getProductDetail } from '../../api/api.js'
import { postCartAdd, getCartCounts } from '../../api/cart.js'
import WxParse from '../../wxParse/wxParse.js'
import util from '../../utils/util.js'
import wxh from '../../utils/wxh.js'

const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    parameter: {
      navbar: '1',
      return: '1',
      title: '商品详情',
    },
    attribute: {
      cartAttr: false,
    }, //属性是否打开
    animated: false, //购物车动画
    id: 0, //商品id
    goodsDetail: {}, //商品详情
    skuLabel: '请选择', //属性页面提示
    skuValue: '', //已选属性
    sku: {}, //系统属性
    spec: [], //规格
    productSelect: {}, //属性选中规格
    num: 1, //购买数量
    sliderImage: [], //图片滑动内容
    isAuto: false, //没有授权的不会自动授权
    iShidden: true, //是否隐藏授权
    isOpen: false, //是否打开属性组件
    isLog: app.globalData.isLog, //是否登录
    actionSheetHidden: true,
    posterImageStatus: false,
    circular: false,
    autoplay: true,
    interval: 3000,
    duration: 500,
    clientHeight: '',
    good_list: [],
    isDown: true,
    storeSelfMention: true,
  },
  /**
   * 登录后加载
   *
   */
  onLoadFun: function (e) {
    this.setData({
      isLog: true,
    })
    this.getCartCount()
    //this.downloadFilePromotionCode();
    //this.getUserInfo();
    //this.get_product_collect();
  },
  /*
   * 获取用户信息
   */
  getUserInfo: function () {
    var that = this
    getUserInfo().then(res => {
      that.setData({
        'sharePacket.isState': res.data.is_promoter ? false : true,
      })
    })
  },
  /**
   * 购物车数量加和数量减
   *
   */
  ChangeCartNum: function (e) {
    //是否 加|减
    var changeValue = e.detail
    //获取当前变动属性
    var productSelect = this.data.productSelect
    //不存在不加数量
    if (productSelect === undefined) return
    //提取库存
    var stock = productSelect.stock || 0
    //设置默认数据
    if (productSelect.num == undefined) productSelect.num = 1
    //数量+
    if (changeValue) {
      productSelect.num++
      //大于库存时,等于库存
      if (productSelect.num > stock) productSelect.num = stock
      this.setData({
        ['productSelect.num']: productSelect.num,
        num: productSelect.num,
      })
    } else {
      //数量减
      productSelect.num--
      //小于1时,等于1
      if (productSelect.num < 1) productSelect.num = 1
      this.setData({
        ['productSelect.num']: productSelect.num,
        num: productSelect.num,
      })
    }
  },
  /**
   * 属性变动赋值
   *
   */
  ChangeAttr: function (e) {
    console.log(e)
    var values = e.detail
    var productSelect = this.data.sku[values]
    console.log(productSelect)
    console.log(values)
    this.setData({
      ['productSelect.image']: productSelect.image,
      ['productSelect.price']: productSelect.price,
      ['productSelect.stock']: productSelect.stock,
      ['productSelect.id']: productSelect.id,
      ['productSelect.num']: 1,
      skuValue: values,
      skuLabel: '已选择',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //扫码携带参数处理
    if (options.scene) {
      var value = util.getUrlParams(decodeURIComponent(options.scene))
      if (value.id) options.id = value.id
    }
    if (!options.id)
      return app.Tips(
        {
          title: '缺少参数无法查看商品',
        },
        {
          tab: 3,
          url: 1,
        }
      )
    this.setData({
      id: options.id,
    })
    this.getGoodsDetails()
  },
  /**
   * 设置优品推荐div高度
   */
  setClientHeight: function () {
    if (!this.data.good_list.length) return
    var query = wx.createSelectorQuery().in(this)
    query.select('#list').boundingClientRect()
    var that = this
    query.exec(function (res) {
      that.setData({
        clientHeight: res[0].height + 20,
      })
    })
  },
  /**
   * 获取产品详情
   *
   */
  getGoodsDetails: function () {
    var that = this
    getProductDetail(that.data.id)
      .then(res => {
        var goodsDetail = res.data
        that.setData({
          goodsDetail: goodsDetail,
          description: goodsDetail.desc,
          sku: goodsDetail.sku || {},
          sliderImage: goodsDetail.sliderImage.split(','),
        })
        that.initSpec()
        that.DefaultSelect()
        that.setClientHeight()
        //html转wxml
        WxParse.wxParse('description', 'html', that.data.description, that, 0)
      })
      .catch(err => {
        //状态异常返回上级页面
        return app.Tips(
          {
            title: err.toString(),
          },
          {
            tab: 3,
            url: 1,
          }
        )
      })
  },
  goPages: function (e) {
    console.log(e, e.currentTarget.dataset.id)
    wx.navigateTo({
      url: 'pages/goods_details/index?id=' + e.currentTarget.dataset.id,
    })
  },
  /**
   * 初始化商品规格
   */
  initSpec: function () {
    let spec = []
    for (let item in this.data.sku) {
      spec.push(item)
    }
    this.setData({ spec: spec })
  },
  /**
   * 默认选中属性
   *
   */
  DefaultSelect: function () {
    var goodsDetail = this.data.goodsDetail
    // 获取sku中第一个sku作为默认选项
    let skuValue = this.data.spec[0]
    let productSelect = this.data.sku[skuValue]
    this.setData({
      ['productSelect.name']: goodsDetail.name,
      ['productSelect.image']: productSelect.image,
      ['productSelect.price']: productSelect.price,
      ['productSelect.stock']: productSelect.stock,
      ['productSelect.id']: productSelect.id,
      ['productSelect.num']: 1,
      skuValue: skuValue,
      skuLabel: '已选择',
    })
  },
  /**
   * 获取是否收藏
   */
  get_product_collect: function () {
    var that = this
    getProductDetail(that.data.id).then(res => {
      that.setData({
        'goodsDetail.userCollect': res.data.goodsDetail.userCollect,
      })
    })
  },
  /**
   *
   *
   * 收藏商品
   */
  setCollect: function () {
    if (app.globalData.isLog === false) {
      this.setData({
        isAuto: true,
        iShidden: false,
      })
    } else {
      var that = this
      if (this.data.goodsDetail.userCollect) {
        collectDel(this.data.goodsDetail.id).then(res => {
          that.setData({
            ['goodsDetail.userCollect']: !that.data.goodsDetail.userCollect,
          })
        })
      } else {
        collectAdd(this.data.goodsDetail.id).then(res => {
          that.setData({
            ['goodsDetail.userCollect']: !that.data.goodsDetail.userCollect,
          })
        })
      }
    }
  },
  /**
   * 打开属性插件
   */
  selecAttr: function () {
    if (app.globalData.isLog === false)
      this.setData({
        isAuto: true,
        iShidden: false,
      })
    else
      this.setData({
        'attribute.cartAttr': true,
        isOpen: true,
      })
  },
  onMyEvent: function (e) {
    this.setData({
      'attribute.cartAttr': e.detail.window,
      isOpen: false,
    })
  },
  /**
   * 打开属性加入购物车
   *
   */
  joinCart: function (e) {
    //是否登录
    if (app.globalData.isLog === false)
      this.setData({
        isAuto: true,
        iShidden: false,
      })
    else {
      this.goCat()
    }
  },
  /*
   * 加入购物车
   */
  goCat: function (isPay) {
    var that = this
    var productSelect = this.data.sku[this.data.skuValue]
    //打开属性
    if (this.data.skuValue) {
      //默认选中了属性，但是没有打开过属性弹窗还是自动打开让用户查看默认选中的属性
      this.setData({
        'attribute.cartAttr': !this.data.isOpen ? true : false,
      })
    } else {
      if (this.data.isOpen)
        this.setData({
          'attribute.cartAttr': true,
        })
      else
        this.setData({
          'attribute.cartAttr': !this.data.attribute.cartAttr,
        })
    }
    //只有关闭属性弹窗时进行加入购物车
    if (this.data.attribute.cartAttr === true && this.data.isOpen == false)
      return this.setData({
        isOpen: true,
      })
    //如果有属性,没有选择,提示用户选择
    if (
      this.data.spec.length &&
      productSelect === undefined &&
      this.data.isOpen == true
    )
      return app.Tips({
        title: '请选择属性',
      })
    postCartAdd({
      productId: that.data.id,
      num: that.data.num,
      skuId: productSelect !== undefined ? productSelect.id : '',
    })
      .then(res => {
        that.setData({
          isOpen: false,
          'attribute.cartAttr': false,
        })
        if (isPay)
          wx.navigateTo({
            url: '/packageB/order_confirm/index?cartId=' + res.data,
          })
        else
          app.Tips(
            {
              title: '添加购物车成功',
              icon: 'success',
            },
            function () {
              that.getCartCount(true)
            }
          )
      })
      .catch(err => {
        console.log(err)
        return app.Tips({
          title: err,
        })
      })
  },
  /**
   * 获取购物车数量
   * @param boolean 是否展示购物车动画和重置属性
   */
  getCartCount: function (isAnima) {
    var that = this
    getCartCounts().then(res => {
      that.setData({
        CartCount: res.data,
      })
      //加入购物车后重置属性
      if (isAnima) {
        that.setData({
          animated: true,
          attrValue: '',
          attr: '请选择',
          ['productSelect.image']: that.data.goodsDetail.image,
          ['productSelect.price']: that.data.goodsDetail.price,
          ['productSelect.stock']: that.data.goodsDetail.stock,
          ['productSelect.id']: '',
          ['productSelect.num']: 1,
        })
        // that.selectComponent('#sku-window').ResetAttr()
        setTimeout(function () {
          that.setData({
            animated: false,
          })
        }, 500)
      }
    })
  },
  /**
   * 立即购买
   */
  goBuy: function (e) {
    var that = this
    if (app.globalData.isLog === false)
      this.setData({
        isAuto: true,
        iShidden: false,
      })
    else {
      this.goCat(true)
    }
  },
  /**
   * 分享打开和关闭
   *
   */
  listenerActionSheet: function () {
    if (app.globalData.isLog === false)
      this.setData({
        isAuto: true,
        iShidden: false,
      })
    else
      this.setData({
        actionSheetHidden: !this.data.actionSheetHidden,
      })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this
    that.setData({
      actionSheetHidden: !that.data.actionSheetHidden,
    })
    return {
      title: that.data.goodsDetail.name || '',
      imageUrl: that.data.goodsDetail.image || '',
      path:
        '/packageB/goods_details/index?id=' +
        that.data.id +
        '&spid=' +
        that.data.uid,
    }
  },
})
